<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.2.3/js/bootstrap.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">

    <title>考试进行中</title>
    <style>
        .question-number {
            width: 40px;
            height: 40px;
            border: 2px solid #ccc;
            border-radius: 50%;
            text-align: center;
            line-height: 40px;
            cursor: pointer;
        }

        .highlight {
            background-color: blue;
            color: white;
        }

        .navbar-brand img {
            width: 50px;
            height: auto;
            margin-right: 10px;
        }

    </style>


</head>
<body>
    <nav class="navbar navbar-expand-md bg-dark navbar-dark">
        <a class="navbar-brand" href="#" th:text="${exam.name}"></a>
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
<!--                <span class="nav-link countdown" th:text="'倒计时: ' + ${exam.timeLimit}"></span>-->
            </li>
        </ul>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8">
                <div id="questionContainer" th:each="examQuestion,examQuestionIndex : ${examQuestions}" th:value="${examQuestion.question.id}">
                    <h2 th:text="${examQuestionIndex.index + 1}"></h2>

                        <div th:with="question=${examQuestion.question}" >

                        <p th:text="${question.description}" ></p>

                    <div class="form-check" th:each="option : ${question.options}">

                        <input class="form-check-input answer-option" type="radio"  name="choice" th:value="${option.choice}"
                               th:data-question-id="${question.id}" th:data-option-choice="${option.choice}"
                               th:id="${'option' + option.id}">
                        <label class="form-check-label" th:for="${'option' + option.id}" th:text="${option.choice}">
                        </label>
                        <label class="form-check-label"  th:for="${'option' +option.id}" th:text="${option.answer}">
                        </label>
                    </div>

                    </div>
                </div>

                <div class="d-flex justify-content-between mt-4">
                    <button class="btn btn-primary" id="prevBtn">上一题</button>
                    <button type="submit" id="submitBtn" class="btn btn-primary">保存</button>

                    <script th:inline="javascript">

                        var url = window.location.href;
                        var examId = null;
                        var studentId = null;

                        var regex = /\/exam\/(\d+)\/student\/(\d+)/;
                        var match = url.match(regex);
                        if (match) {
                            examId = match[1];
                            studentId = match[2];
                        }

                        console.log("examId:", examId);
                        console.log("studentId:", studentId);

                        var questionContainers = Array.from(document.querySelectorAll('#questionContainer'));

                        questionContainers.forEach(function (questionCotainer) {
                            var questionId = questionCotainer.getAttribute('value');
                                localStorage.setItem('question_' + questionId, null);
                        })

                        localStorage.removeItem('question_null');
                        console.log(localStorage)

                        var answerOptionsContainers = Array.from(document.querySelectorAll('.form-check'));
                        answerOptionsContainers.forEach(function(answerOptionsContainer) {
                            answerOptionsContainer.addEventListener('change', function(event) {
                                var selectedOption = event.target.getAttribute('data-option-choice');
                                var questionId = event.target.getAttribute('data-question-id');
                                localStorage.setItem('question_' + questionId, selectedOption);
                            });
                        });


                        document.getElementById('submitBtn').addEventListener('click', function() {
                            var answers = [];
                            var confirmation = confirm("确认提交吗？");
                            if(confirmation){
                                for (var key in localStorage) {
                                    if (localStorage.hasOwnProperty(key)) {
                                        if (key.startsWith('question_')) {
                                            var questionId = key.substring(9);
                                            var selectedOption = localStorage.getItem(key);
                                            console.log('选择的选项：', selectedOption);
                                            console.log('问题ID：', questionId);
                                            if(selectedOption === null){
                                                alert("您还有题目未选择答案，请完成所有题目后再提交。");
                                                return;
                                            }
                                            var answer = {
                                                choice: selectedOption,
                                                examId: examId,
                                                studentId: studentId,
                                                questionId: questionId
                                            };
                                            answers.push(answer);
                                        }
                                    }
                                }

                                fetch('/api/answer/save-answer', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify(answers)
                                })
                                    .then(response => response.json())
                                    .then(data => {
                                        console.log(data);
                                        alert("成功交卷！");
                                        window.location.href = "/landing";
                                    })
                                    .catch(error => {
                                        console.error(error);
                                    });
                                localStorage.clear();

                            }
                            else{

                            }

                        });

                    </script>

                    <button class="btn btn-primary" id="nextBtn">下一题</button>


                </div>

            </div>

            <div class="col-md-1"></div>

            <div class="col-md-2">
                <div class="d-flex flex-wrap" id="question-list">
                    <div class="border border-dark rounded p-2">
                        <div class="d-flex justify-content-center mb-3">
                            <h4>答题卡</h4>
                        </div>
                        <div class="d-flex flex-wrap justify-content-center">
                            <div class="question-number mr-2 mb-2 border border-dark rounded-circle" th:each="question, questionIndex : ${examQuestions}" th:data-question="${questionIndex.index + 1}" th:text="${questionIndex.index + 1}"></div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const questionNumbers = document.querySelectorAll('.question-number');
            const questionContents = document.querySelectorAll('#questionContainer');

            let currentQuestionIndex = 0;


            let selections = [];

            function showCurrentQuestion() {
                for (let i = 0; i < questionContents.length; i++) {
                    questionContents[i].style.display = 'none';
                }
                questionContents[currentQuestionIndex].style.display = 'block';

                restoreSelections();
            }

            function saveSelections() {
                const currentQuestion = questionContents[currentQuestionIndex];
                const selectedOption = currentQuestion.querySelector('input[type="radio"]:checked');

                if (selectedOption) {
                    const choice = selectedOption.getAttribute('data-option-choice');
                    selections[currentQuestionIndex] = { questionNumber: currentQuestionIndex + 1, choice };
                } else {
                    selections[currentQuestionIndex] = null;
                }
            }

            function restoreSelections() {
                const selectedOption = selections[currentQuestionIndex];
                if (selectedOption) {
                    const option = questionContents[currentQuestionIndex].querySelector(`input[data-option-choice="${selectedOption.choice}"]`);
                    option.checked = true;
                }
            }

            questionNumbers.forEach(function (questionNumber, index) {
                questionNumber.addEventListener('click', function () {
                    saveSelections();

                    currentQuestionIndex = index;
                    showCurrentQuestion();

                    questionNumbers.forEach(function (qn) {
                        qn.classList.remove('highlight');
                    });
                    questionNumber.classList.add('highlight');
                });
            });

            document.getElementById('prevBtn').addEventListener('click', function () {
                if (currentQuestionIndex > 0) {
                    saveSelections();

                    currentQuestionIndex--;
                    showCurrentQuestion();

                    questionNumbers.forEach(function (qn) {
                        qn.classList.remove('highlight');
                    });
                    questionNumbers[currentQuestionIndex].classList.add('highlight');
                }
            });

            document.getElementById('nextBtn').addEventListener('click', function () {
                if (currentQuestionIndex < questionNumbers.length - 1) {
                    saveSelections();

                    currentQuestionIndex++;
                    showCurrentQuestion();

                    questionNumbers.forEach(function (qn) {
                        qn.classList.remove('highlight');
                    });
                    questionNumbers[currentQuestionIndex].classList.add('highlight');
                }
            });

            showCurrentQuestion();
            questionNumbers[0].classList.add('highlight');
        });


    </script>
</body>
</html>
